/**
 * 业务图层模块
 * @description 基于项目业务需求封装的专用图层管理，包括杆塔、线路、变电站等业务图层
 */

import { ref, reactive } from 'vue';
import { ASSETS, LABEL_STYLES } from '../constants/index.js';
import { SUBSTATION_CONFIG } from '../constants/business.js';
import { 
  QUESTION_CONFIG, 
  MONITORING_RESULT_CONFIG,
  getQuestionVectorType,
  getQuestionColor,
  getQuestionIcon 
} from '../constants/monitoring.js';
import yellowLine from '@/assets/images/line-color-yellow.png';

/**
 * 业务图层管理器类
 * @class BusinessLayers
 */
export class BusinessLayers {
  constructor(mapEngine, layerManager) {
    this.mapEngine = mapEngine;
    this.layerManager = layerManager;
    this.businessLayers = new Map();
    
    // 业务图层配置
    this.layerConfigs = reactive({
      tower: {
        icon: ASSETS.icons.tower,
        style: {
          scale: 0.8,
          scaleByDistance: new Cesium.NearFarScalar(1000, 1, 10000, 0.1),
          clampToGround: true
        },
        label: LABEL_STYLES.default,
        popup: {
          template: `
            <div class="tower-popup">
              <h4>{towerName}</h4>
              <p>杆塔编号: {towerCode}</p>
              <p>经纬度: {lng}, {lat}</p>
              <p>海拔高度: {alt}m</p>
            </div>
          `,
          maxWidth: 300
        }
      },
      line: {
        style: {
          color: '#ffff00',
          width: 3,
          clampToGround: true,
          materialType: mars3d.MaterialType.LineFlow,
          materialOptions: {
            color: '#ffff00',
            speed: 10,
            repeat: 5
          }
        },
        label: LABEL_STYLES.project,
        popup: {
          template: `
            <div class="line-popup">
              <h4>{lineName}</h4>
              <p>线路编号: {lineCode}</p>
              <p>电压等级: {voltage}kV</p>
              <p>线路长度: {length}km</p>
            </div>
          `,
          maxWidth: 300
        }
      },
      substation: {
        icon: SUBSTATION_CONFIG.ICONS.DESIGN, // 默认使用设计变电站图标
        style: {
          scale: 1.0,
          scaleByDistance: new Cesium.NearFarScalar(500, 1, 5000, 0.1),
          clampToGround: true
        },
        polygonStyle: {
          color: `${SUBSTATION_CONFIG.COLORS.DESIGN}4D`, // 30% 透明度
          outline: true,
          outlineColor: SUBSTATION_CONFIG.COLORS.DESIGN,
          outlineWidth: 2,
          clampToGround: true
        },
        label: LABEL_STYLES.project,
        popup: {
          template: `
            <div class="substation-popup">
              <h4>{stationName}</h4>
              <p>变电站编号: {stationCode}</p>
              <p>电压等级: {voltage}kV</p>
              <p>容量: {capacity}MVA</p>
              <p>状态: {status}</p>
            </div>
          `,
          maxWidth: 350
        }
      },
      sensitiveArea: {
        style: {
          color: 'rgba(255, 0, 0, 0.2)',
          outline: true,
          outlineColor: '#ff0000',
          outlineWidth: 2,
          outlineStyle: {
            materialType: mars3d.MaterialType.Color,
            materialOptions: {
              color: '#ff0000',
              dashLength: 8.0
            }
          },
          clampToGround: true
        },
        label: {
          font_size: 16,
          color: '#ff0000',
          background: true,
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          padding: [5, 10]
        },
        popup: {
          template: `
            <div class="sensitive-area-popup">
              <h4>{areaName}</h4>
              <p>区域类型: {areaType}</p>
              <p>保护等级: {protectionLevel}</p>
              <p>面积: {area}平方公里</p>
              <p>管理单位: {managementUnit}</p>
            </div>
          `,
          maxWidth: 350
        }
      }
    });
  }

  /**
   * 获取地图实例
   * @private
   * @returns {mars3d.Map|null} 地图实例
   */
  _getMap() {
    return this.mapEngine?.getInstance() || null;
  }

  /**
   * 添加杆塔图层
   * @param {Object} options - 杆塔图层配置
   * @param {string} options.url - 数据URL
   * @param {Array} options.data - GeoJSON数据
   * @param {string} options.id - 图层ID
   * @param {string} options.projectName - 项目名称
   * @param {Object} options.style - 自定义样式
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 杆塔图层实例
   */
  addTowerLayer(options = {}) {
    const {
      url,
      data,
      id = `tower_${Date.now()}`,
      projectName = '杆塔图层',
      style = {},
      flyTo = false
    } = options;

    const layerConfig = {
      type: 'vector',
      id,
      url,
      data,
      flyTo,
      style: {
        type: 'billboardP',
        styleOptions: {
          image: this.layerConfigs.tower.icon,
          ...this.layerConfigs.tower.style,
          ...style,
          label: {
            text: '{towerName}',
            ...this.layerConfigs.tower.label
          }
        }
      },
      popup: this.layerConfigs.tower.popup
    };

    const layer = this.layerManager.addVectorLayer(layerConfig);
    if (layer) {
      this.businessLayers.set(id, {
        type: 'tower',
        layer,
        config: layerConfig,
        metadata: { projectName }
      });

      // 绑定业务事件
      this._bindTowerEvents(layer, id);
    }

    return layer;
  }

  /**
   * 添加塔位矢量图层
   * @param {Object} options - 塔位图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {string} options.projectName - 项目名称
   * @param {string} options.icon - 图标路径
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 塔位图层实例
   */
  addVectorTower(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      projectName,
      icon,
      flyTo = false
    } = options;

    // 使用与CustomMap相同的配置创建GeoJsonLayer
    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    const graphicLayer = new mars3d.layer.GeoJsonLayer({
      id: id,
      name: name,
      url: baseUrl + url,
      symbol: {
        merge: true,
        styleOptions: {
          image: icon || this.layerConfigs.tower.icon,
          scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true,
          label: {
            text: '{towerName}',
            font_size: 14,
            color: "#ffffff",
            background: true,
            backgroundColor: 'rgb(0,172,199)',
            pixelOffsetY: -70,
            pixelOffsetScaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
          },
        }
      },
      flyTo: flyTo,
      flyToOptions: {
        duration: .5
      }
    });

    map.addLayer(graphicLayer);

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'tower',
      layer: graphicLayer,
      config: options,
      metadata: { projectName }
    });

    return graphicLayer;
  }

  /**
   * 添加线路矢量图层 (与CustomMap兼容)
   * @param {Object} options - 线路矢量图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {string} options.color - 线路颜色
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 线路矢量图层实例
   */
  addVectorLine(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      color = '#3ACC8E',
      flyTo = false
    } = options;

    // 创建GeoJsonLayer
    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    const graphicLayer = new mars3d.layer.GeoJsonLayer({
      id: id,
      name: name,
      url: baseUrl + url,
      queryParameters: {},
      symbol: {
        merge: true,
        styleOptions: {
          width: 6,
          sharpness: 0.95,
          materialType: mars3d.MaterialType.PolylineOutline,
          materialOptions: {
            color: color,
            outlineWidth: 1,
            outlineColor: Cesium.Color.BLACK
          },
          clampToGround: true,
          label: {
            text: '{section}',
            font_size: 18,
            font_weight: 'bold',
            color: "#ffffff",
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 500000,
            distanceDisplayCondition_near: 0
          }
        }
      },
      flyTo: flyTo,
      flyToOptions: {
        duration: .5
      }
    });

    map.addLayer(graphicLayer);

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'vectorLine',
      layer: graphicLayer,
      config: options
    });

    return graphicLayer;
  }

  /**
   * 添加变电站矢量图层
   * @param {Object} options - 变电站矢量图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {number} options.vectorType - 变电站类型 (1: 设计, 2: 施工)
   * @param {string} options.color - 自定义颜色，覆盖默认颜色
   * @param {string} options.icon - 自定义图标，覆盖默认图标
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 变电站矢量图层实例
   */
  addVectorSubStation(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      vectorType = SUBSTATION_CONFIG.TYPES.DESIGN,
      color = null,
      icon = null,
      flyTo = false
    } = options;

    // 根据类型获取颜色和图标，支持自定义覆盖
    const substationColor = color || (vectorType == SUBSTATION_CONFIG.TYPES.DESIGN 
      ? SUBSTATION_CONFIG.COLORS.DESIGN 
      : SUBSTATION_CONFIG.COLORS.CONSTRUCTION);
      
    const substationIcon = icon || (vectorType == SUBSTATION_CONFIG.TYPES.DESIGN 
      ? SUBSTATION_CONFIG.ICONS.DESIGN 
      : SUBSTATION_CONFIG.ICONS.CONSTRUCTION);

    // 先移除已存在的同ID图层
    this.removeVectorById(id);
    // 创建组图层
    const groupLayer = new mars3d.layer.GroupLayer({
      id: id
    });

    // 创建GeoJsonLayer
    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    const polygonLayer = new mars3d.layer.GeoJsonLayer({
      name: name,
      url: baseUrl + url,
      symbol: {
        styleOptions: {
          scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true,
          materialType: mars3d.MaterialType.Polygon,
          materialOptions: {
            color: substationColor,
            opacity: 0.3,
          },
          outline: true,
          outlineWidth: 2.5,
          outlineStyle: {
            materialType: mars3d.MaterialType.Color,
            materialOptions: {
              color: substationColor,
              dashLength: 12.0
            }
          }
        }
      },
      flyTo: flyTo,
      flyToOptions: {
        duration: .5,
        radius: 300
      }
    });

    groupLayer.addLayer(polygonLayer);

    // 获取矢量面中心点并创建图标实体
    polygonLayer.on(mars3d.EventType.load, function(event) {
      // 获取图层中心点 (这里需要根据实际数据计算中心点)
      const graphics = polygonLayer.getGraphics();
      let center = null;
      
      if (graphics && graphics.length > 0) {
        // 简单获取第一个图形的中心点
        const firstGraphic = graphics[0];
        if (firstGraphic && firstGraphic.position) {
          center = firstGraphic.position;
        } else if (firstGraphic && firstGraphic.positions && firstGraphic.positions.length > 0) {
          // 如果是多边形，计算中心点
          const positions = firstGraphic.positions;
          let totalLng = 0, totalLat = 0;
          positions.forEach(pos => {
            const cartographic = Cesium.Cartographic.fromCartesian(pos);
            totalLng += Cesium.Math.toDegrees(cartographic.longitude);
            totalLat += Cesium.Math.toDegrees(cartographic.latitude);
          });
          center = [totalLng / positions.length, totalLat / positions.length];
        }
      }

      if (center) {
        // 创建图标实体
        const billboard = new mars3d.graphic.BillboardEntity({
          position: center,
          style: {
            image: substationIcon,
            scaleByDistance: new Cesium.NearFarScalar(360, 1, 3600, 0.1),
            clampToGround: true,
            width: 60,
            height: 64,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            label: {
              text: name,
              font_size: 18,
              color: '#ffffff',
              background: true,
              backgroundColor: '#4656b2',
              pixelOffsetY: -88,
              pixelOffsetScaleByDistance: new Cesium.NearFarScalar(360, 1, 3600, 0.1),
              scaleByDistance: new Cesium.NearFarScalar(360, 1, 3600, 0.1),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000)
            },
          }
        });

        // 将图标添加到多边形图层
        polygonLayer.addGraphic(billboard);
      }
    });

    // 将组添加到地图
    map.addLayer(groupLayer);

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'vectorSubStation',
      layer: groupLayer,
      config: options
    });

    return groupLayer;
  }

  /**
   * 添加线路图层
   * @param {Object} options - 线路图层配置
   * @param {string} options.url - 数据URL
   * @param {Array} options.data - GeoJSON数据
   * @param {string} options.id - 图层ID
   * @param {string} options.projectName - 项目名称
   * @param {string} options.color - 线路颜色
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 线路图层实例
   */
  addLineLayer(options = {}) {
    const {
      url,
      data,
      id = `line_${Date.now()}`,
      projectName = '线路图层',
      color = '#ffff00',
      flyTo = false
    } = options;

    const layerConfig = {
      type: 'vector',
      id,
      url,
      data,
      flyTo,
      style: {
        type: 'polylineP',
        styleOptions: {
          ...this.layerConfigs.line.style,
          color,
          materialOptions: {
            ...this.layerConfigs.line.style.materialOptions,
            color
          },
          label: {
            text: '{lineName}',
            ...this.layerConfigs.line.label
          }
        }
      },
      popup: this.layerConfigs.line.popup
    };

    const layer = this.layerManager.addVectorLayer(layerConfig);
    if (layer) {
      this.businessLayers.set(id, {
        type: 'line',
        layer,
        config: layerConfig,
        metadata: { projectName, color }
      });

      // 绑定业务事件
      this._bindLineEvents(layer, id);
    }

    return layer;
  }

  /**
   * 添加变电站图层
   * @param {Object} options - 变电站图层配置
   * @param {string} options.url - 数据URL
   * @param {Array} options.data - GeoJSON数据
   * @param {string} options.id - 图层ID
   * @param {number} options.vectorType - 矢量类型 (1: 设计阶段, 其他: 建设阶段)
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 变电站图层实例
   */
  addSubstationLayer(options = {}) {
    const {
      url,
      data,
      id = `substation_${Date.now()}`,
      vectorType = 1,
      flyTo = false
    } = options;

    const map = this._getMap();
    if (!map) return null;

    // 移除同ID的旧图层
    this.removeBusinessLayer(id);

    // 创建组图层
    const groupLayer = new mars3d.layer.GroupLayer({ id });

    // 创建多边形图层
    const polygonLayer = new mars3d.layer.GeoJsonLayer({
      name: `变电站_${id}`,
      url,
      data,
      symbol: {
        type: 'polygonP',
        styleOptions: {
          ...this.layerConfigs.substation.polygonStyle,
          materialOptions: {
            color: vectorType === SUBSTATION_CONFIG.TYPES.DESIGN 
              ? SUBSTATION_CONFIG.COLORS.DESIGN 
              : SUBSTATION_CONFIG.COLORS.CONSTRUCTION,
            opacity: 0.3
          },
          outlineStyle: {
            materialType: mars3d.MaterialType.Color,
            materialOptions: {
              color: vectorType === SUBSTATION_CONFIG.TYPES.DESIGN 
                ? SUBSTATION_CONFIG.COLORS.DESIGN 
                : SUBSTATION_CONFIG.COLORS.CONSTRUCTION,
              dashLength: 12.0
            }
          }
        }
      },
      flyTo: false,
      popup: this.layerConfigs.substation.popup
    });

    // 监听多边形图层加载完成，添加图标
    polygonLayer.on(mars3d.EventType.load, (event) => {
      if (event.graphics && event.graphics.length > 0) {
        event.graphics.forEach(graphic => {
          const center = graphic.center;
          const properties = graphic.attr || {};
          
          // 创建图标
          const billboard = new mars3d.graphic.BillboardEntity({
            position: center,
            style: {
              image: this.layerConfigs.substation.icon,
              ...this.layerConfigs.substation.style,
              label: {
                text: properties.stationName || '变电站',
                ...this.layerConfigs.substation.label,
                pixelOffsetY: -88
              }
            },
            attr: properties
          });
          
          polygonLayer.addGraphic(billboard);
        });
      }
    });

    groupLayer.addLayer(polygonLayer);
    map.addLayer(groupLayer);

    if (flyTo) {
      setTimeout(() => {
        groupLayer.flyTo({ duration: 1.0 });
      }, 500);
    }

    // 存储业务图层信息
    this.businessLayers.set(id, {
      type: 'substation',
      layer: groupLayer,
      polygonLayer,
      config: options,
      metadata: { vectorType }
    });

    return groupLayer;
  }

  /**
   * 添加敏感区域图层
   * @param {Object} options - 敏感区域配置
   * @param {string} options.url - 数据URL
   * @param {Array} options.data - GeoJSON数据
   * @param {string} options.id - 图层ID
   * @param {Array} options.projectCodes - 关联项目代码
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 敏感区域图层实例
   */
  addSensitiveAreaLayer(options = {}) {
    const {
      url,
      data,
      id = `sensitive_area_${Date.now()}`,
      projectCodes = [],
      flyTo = false
    } = options;

    const layerConfig = {
      type: 'vector',
      id,
      url,
      data,
      flyTo,
      style: {
        type: 'polygonP',
        styleOptions: {
          ...this.layerConfigs.sensitiveArea.style,
          label: {
            text: '{areaName}',
            ...this.layerConfigs.sensitiveArea.label
          }
        }
      },
      popup: this.layerConfigs.sensitiveArea.popup
    };

    const layer = this.layerManager.addVectorLayer(layerConfig);
    if (layer) {
      this.businessLayers.set(id, {
        type: 'sensitiveArea',
        layer,
        config: layerConfig,
        metadata: { projectCodes }
      });

      // 绑定业务事件
      this._bindSensitiveAreaEvents(layer, id);
    }

    return layer;
  }

  /**
   * 添加敏感区分析图层（基于原useMapLayerMethods的addAnalyseLayer）
   * @param {Object} options - 敏感区分析图层配置
   * @param {string} options.url - 数据URL路径
   * @param {Object} options.data - GeoJSON数据
   * @param {string} options.id - 图层ID
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @param {Object} options.styleOptions - 样式配置
   * @param {string} options.styleOptions.color - 填充颜色
   * @param {number} options.styleOptions.opacity - 透明度
   * @param {boolean} options.styleOptions.outline - 是否显示边框
   * @param {string} options.styleOptions.outlineColor - 边框颜色
   * @param {number} options.styleOptions.outlineWidth - 边框宽度
   * @param {Function} options.filter - 数据过滤函数
   * @param {boolean|string} options.popup - 弹窗配置
   * @returns {Object|null} 敏感区分析图层实例
   */
  addSensitiveAnalyseLayer(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      url,
      data,
      id = `sensitive_analyse_${Date.now()}`,
      flyTo = false,
      styleOptions = {},
      filter,
      popup = false
    } = options;

    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    
    // 构建数据源配置
    let dataConfig = {};
    if (url) {
      dataConfig.url = baseUrl + url;
    } else if (data) {
      dataConfig.data = data;
    } else {
      console.warn('addSensitiveAnalyseLayer: 需要提供url或data参数');
      return null;
    }

    // 默认样式配置
    const defaultStyleOptions = {
      color: '#FF3030',
      opacity: 0.6,
      outline: true,
      outlineColor: '#FFFFFF',
      outlineWidth: 2,
      clampToGround: true
    };

    const finalStyleOptions = { ...defaultStyleOptions, ...styleOptions };

    const layerConfig = {
      name: 'sensitiveAnalyseLayer',
      id,
      ...dataConfig,
      flyTo,
      flyToOptions: {
        duration: 0.5
      },
      filter: filter || function(feature) {
        return feature; // 默认显示所有要素
      },
      symbol: {
        type: 'polygon',
        styleOptions: finalStyleOptions,
        highlight: {
          type: 'polygon',
          styleOptions: {
            color: '#00FF0080',
            outlineColor: '#FFFF00',
            outlineWidth: 3
          }
        }
      },
      popup: popup
    };

    try {
      const layer = new mars3d.layer.GeoJsonLayer(layerConfig);
      map.addLayer(layer);

      // 缓存图层信息
      this.businessLayers.set(id, {
        type: 'sensitiveAnalyse',
        layer,
        config: layerConfig,
        metadata: {}
      });

      return layer;
    } catch (error) {
      console.error('添加敏感区分析图层失败:', error);
      return null;
    }
  }

  /**
   * 添加监测结果图层
   * @param {Object} options - 监测结果配置
   * @param {string} options.url - 数据URL
   * @param {string} options.id - 图层ID
   * @param {string} options.periodId - 期次ID
   * @param {string} options.questionType - 问题类型
   * @param {boolean} options.flyTo - 是否飞行到图层
   * @returns {Object|null} 监测结果图层实例
   */
  addMonitoringResultLayer(options = {}) {
    const {
      url,
      id = `monitoring_result_${Date.now()}`,
      periodId,
      questionType,
      flyTo = false
    } = options;

    // 根据问题类型设置不同样式
    const questionStyles = {
      '植被破坏': { color: '#ff0000', icon: '/assets/icons/vegetation-damage.png' },
      '水土流失': { color: '#ff8800', icon: '/assets/icons/soil-erosion.png' },
      '违法建设': { color: '#ff0088', icon: '/assets/icons/illegal-construction.png' },
      '其他': { color: '#888888', icon: '/assets/icons/other-issue.png' }
    };

    const styleConfig = questionStyles[questionType] || questionStyles['其他'];

    const layerConfig = {
      type: 'vector',
      id,
      url,
      flyTo,
      style: {
        type: 'polygonP',
        styleOptions: {
          color: `${styleConfig.color}40`, // 添加透明度
          outline: true,
          outlineColor: styleConfig.color,
          outlineWidth: 2,
          clampToGround: true,
          label: {
            text: '{问题描述}',
            font_size: 14,
            color: '#ffffff',
            background: true,
            backgroundColor: styleConfig.color,
            padding: [3, 8]
          }
        }
      },
      popup: {
        template: `
          <div class="monitoring-result-popup">
            <h4>监测问题详情</h4>
            <p>问题类型: {问题类型}</p>
            <p>问题描述: {问题描述}</p>
            <p>发现时间: {发现时间}</p>
            <p>严重程度: {严重程度}</p>
            <p>处理状态: {处理状态}</p>
          </div>
        `,
        maxWidth: 400
      }
    };

    const layer = this.layerManager.addVectorLayer(layerConfig);
    if (layer) {
      this.businessLayers.set(id, {
        type: 'monitoringResult',
        layer,
        config: layerConfig,
        metadata: { periodId, questionType }
      });
    }

    return layer;
  }

  /**
   * 绑定杆塔事件
   * @private
   * @param {Object} layer - 图层实例
   * @param {string} layerId - 图层ID
   */
  _bindTowerEvents(layer, layerId) {
    layer.on(mars3d.EventType.click, (event) => {
      const graphic = event.graphic;
      const properties = graphic.attr || {};
      
      // 触发杆塔点击事件
      this._triggerBusinessEvent('towerClick', {
        layerId,
        graphic,
        properties,
        position: event.cartesian
      });
    });

    layer.on(mars3d.EventType.load, () => {
      console.log(`杆塔图层 ${layerId} 加载完成`);
    });
  }

  /**
   * 绑定线路事件
   * @private
   * @param {Object} layer - 图层实例
   * @param {string} layerId - 图层ID
   */
  _bindLineEvents(layer, layerId) {
    layer.on(mars3d.EventType.click, (event) => {
      const graphic = event.graphic;
      const properties = graphic.attr || {};
      
      // 触发线路点击事件
      this._triggerBusinessEvent('lineClick', {
        layerId,
        graphic,
        properties,
        position: event.cartesian
      });
    });
  }

  /**
   * 绑定敏感区域事件
   * @private
   * @param {Object} layer - 图层实例
   * @param {string} layerId - 图层ID
   */
  _bindSensitiveAreaEvents(layer, _layerId) {
    layer.on(mars3d.EventType.click, (event) => {
      const graphic = event.graphic;
      const properties = graphic.attr || {};
      
      // 触发敏感区域点击事件
      this._triggerBusinessEvent('sensitiveAreaClick', {
        layerId,
        graphic,
        properties,
        position: event.cartesian
      });
    });
  }

  /**
   * 触发业务事件
   * @private
   * @param {string} eventType - 事件类型
   * @param {Object} data - 事件数据
   */
  _triggerBusinessEvent(eventType, data) {
    // 这里可以添加事件总线或回调机制
    console.log(`Business event: ${eventType}`, data);
  }

  /**
   * 移除业务图层
   * @param {string} id - 图层ID
   * @returns {boolean} 是否成功移除
   */
  removeBusinessLayer(id) {
    const businessLayer = this.businessLayers.get(id);
    if (!businessLayer) return false;

    // 从地图中移除图层
    const success = this.layerManager.removeLayer(id);
    
    if (success) {
      this.businessLayers.delete(id);
    }

    return success;
  }

  /**
   * 删除矢量图层 (兼容CustomMap API)
   * @param {string} id - 图层ID
   * @returns {boolean} 是否成功删除
   */
  removeVectorById(id) {
    const map = this._getMap();
    if (!map) return false;

    // 先尝试从业务图层缓存中删除
    const businessLayer = this.businessLayers.get(id);
    if (businessLayer) {
      this.businessLayers.delete(id);
    }

    // 从地图中获取并删除图层
    const oldLayer = map.getLayerById(id);
    if (oldLayer) {
      map.removeLayer(oldLayer, true);
      return true;
    }

    return false;
  }

  /**
   * 获取业务图层信息
   * @param {string} id - 图层ID
   * @returns {Object|null} 业务图层信息
   */
  getBusinessLayer(id) {
    return this.businessLayers.get(id) || null;
  }

  /**
   * 获取所有业务图层
   * @param {string} type - 图层类型过滤
   * @returns {Array} 业务图层数组
   */
  getAllBusinessLayers(type = null) {
    const layers = Array.from(this.businessLayers.values());
    return type ? layers.filter(layer => layer.type === type) : layers;
  }

  /**
   * 切换业务图层显示状态
   * @param {string} id - 图层ID
   * @param {boolean} visible - 是否显示
   */
  toggleBusinessLayerVisibility(id, visible = null) {
    const businessLayer = this.businessLayers.get(id);
    if (!businessLayer) return;

    const newVisibility = visible !== null ? visible : !businessLayer.layer.show;
    businessLayer.layer.show = newVisibility;
  }

  /**
   * 批量添加业务图层
   * @param {Array} layerConfigs - 图层配置数组
   * @returns {Array} 创建的图层数组
   */
  addBusinessLayersBatch(layerConfigs = []) {
    const createdLayers = [];

    layerConfigs.forEach(config => {
      try {
        let layer = null;
        
        switch (config.type) {
          case 'tower':
            layer = this.addTowerLayer(config);
            break;
          case 'line':
            layer = this.addLineLayer(config);
            break;
          case 'substation':
            layer = this.addSubstationLayer(config);
            break;
          case 'sensitiveArea':
            layer = this.addSensitiveAreaLayer(config);
            break;
          case 'monitoringResult':
            layer = this.addMonitoringResultLayer(config);
            break;
          default:
            console.warn(`Unsupported business layer type: ${config.type}`);
        }
        
        if (layer) {
          createdLayers.push(layer);
        }
      } catch (error) {
        console.error('Error creating business layer:', error, config);
      }
    });

    return createdLayers;
  }

  /**
   * 清除所有业务图层
   * @param {string} type - 指定类型（可选）
   */
  clearAllBusinessLayers(type = null) {
    const layersToRemove = type 
      ? Array.from(this.businessLayers.entries()).filter(([_id, layer]) => layer.type === type)
      : Array.from(this.businessLayers.entries());

    layersToRemove.forEach(([id]) => {
      this.removeBusinessLayer(id);
    });
  }

  /**
   * 获取业务图层统计信息
   * @returns {Object} 统计信息
   */
  getBusinessLayerStatistics() {
    const stats = {
      total: this.businessLayers.size,
      byType: {},
      visible: 0
    };

    this.businessLayers.forEach((layerInfo) => {
      const type = layerInfo.type;
      stats.byType[type] = (stats.byType[type] || 0) + 1;
      
      if (layerInfo.layer.show) {
        stats.visible++;
      }
    });

    return stats;
  }

  /**
   * 更新图层配置
   * @param {string} type - 图层类型
   * @param {Object} config - 新配置
   */
  updateLayerConfig(type, config) {
    if (this.layerConfigs[type]) {
      Object.assign(this.layerConfigs[type], config);
    }
  }

  /**
   * 添加面矢量图层
   * @param {Object} options - 面矢量图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {string} options.projectName - 项目名称
   * @param {number} options.type - 图层类型
   * @param {Object} options.style - 样式配置
   * @param {string} options.icon - 图标路径，如果提供则在面中心添加图标
   * @param {function} options.loaded - 加载完成回调
   * @returns {Object|null} 面矢量图层实例
   */
  addPolygonJson(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      projectName,
      type,
      style,
      icon,
      loaded
    } = options;

    // 移除已存在的图层
    this.removeVectorById(id);

    // 获取API基础URL
    const baseUrl = import.meta.env.VITE_APP_BASE_API;

    // 公共样式生成函数
    function getPolygonSymbol(type, style) {
      if (type == 1) {
        return {};
      }
      return {
        merge: true,
        styleOptions: {
          clampToGround: true,
          materialType: mars3d.MaterialType.Polygon,
          materialOptions: {
            color: style?.fillColor || '#FF3030',
            opacity: 0.3,
          },
          outline: true,
          outlineWidth: 2.5,
          outlineStyle: {
            materialType: style?.outLineType == 'dashed'
              ? mars3d.MaterialType.PolylineDash
              : mars3d.MaterialType.Color,
            materialOptions: {
              color: style?.strokeColor || '#FF3030',
              dashLength: 12.0
            }
          },
          label: {
            text: '{name}',
            font_size: 14,
            color: "#ffffff",
            background: true,
            backgroundColor: 'rgb(0,172,199)',
            pixelOffsetY: -70,
            pixelOffsetScaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
          }
        }
      };
    }

    // 图标实体生成函数
    function addPolygonCenterBillboard(polygonLayer, icon, name) {
      polygonLayer.on(mars3d.EventType.load, (event) => {
        if (event.graphics && event.graphics.length > 0) {
          event.graphics.forEach(graphic => {
            let center = null;
            const properties = graphic.attr || {};

            if (graphic.center) {
              center = graphic.center;
            } else if (graphic.positions && graphic.positions.length > 0) {
              const positions = graphic.positions;
              let totalLng = 0, totalLat = 0;
              positions.forEach(pos => {
                const cartographic = Cesium.Cartographic.fromCartesian(pos);
                totalLng += Cesium.Math.toDegrees(cartographic.longitude);
                totalLat += Cesium.Math.toDegrees(cartographic.latitude);
              });
              center = [totalLng / positions.length, totalLat / positions.length];
            }

            if (center) {
              const billboard = new mars3d.graphic.BillboardEntity({
                position: center,
                style: {
                  image: icon,
                  scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
                  horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  clampToGround: true,
                  width: 60,
                  height: 64,
                  label: {
                    text: properties.name || name || '',
                    font_size: 14,
                    color: '#ffffff',
                    background: true,
                    backgroundColor: 'rgb(0,172,199)',
                    pixelOffsetY: -88,
                    pixelOffsetScaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
                    scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000)
                  }
                },
                attr: properties
              });
              polygonLayer.addGraphic(billboard);
            }
          });
        }
      });
    }

    let mainLayer;

    if (icon) {
      // 有图标，使用组图层
      const groupLayer = new mars3d.layer.GroupLayer({ id });

      const polygonLayer = new mars3d.layer.GeoJsonLayer({
        name: "面矢量图层",
        url: baseUrl + url,
        queryParameters: {},
        symbol: getPolygonSymbol(type, style),
        flyTo: true,
      });

      addPolygonCenterBillboard(polygonLayer, icon, name);

      // 加载完成回调
      if (loaded && typeof loaded === 'function') {
        polygonLayer.on(mars3d.EventType.load, () => {
          loaded(groupLayer);
        });
      }

      groupLayer.addLayer(polygonLayer);
      map.addLayer(groupLayer);
      mainLayer = groupLayer;
    } else {
      // 无图标，直接加图层
      const graphicLayer = new mars3d.layer.GeoJsonLayer({
        id: id,
        name: "面矢量图层",
        url: baseUrl + url,
        queryParameters: {},
        symbol: getPolygonSymbol(type, style),
        flyTo: true,
      });

      map.addLayer(graphicLayer);

      if (loaded && typeof loaded === 'function') {
        graphicLayer.on(mars3d.EventType.load, function () {
          loaded(graphicLayer);
        });
      }

      mainLayer = graphicLayer;
    }

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'polygonJson',
      layer: mainLayer,
      config: options,
      metadata: { projectName }
    });

    return mainLayer;
  }

  /**
   * 添加线矢量图层
   * @param {Object} options - 线矢量图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {string} options.projectName - 项目名称
   * @param {number} options.type - 图层类型
   * @param {string} options.color - 线条颜色
   * @returns {Object|null} 线矢量图层实例
   */
  addPolylineJson(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      projectName,
      type,
      color = '#00CCFF'
    } = options;

    // 获取API基础URL
    const baseUrl = import.meta.env.VITE_APP_BASE_API;

    // 创建GeoJsonLayer
    const graphicLayer = new mars3d.layer.GeoJsonLayer({
      id: id,
      name: "线矢量图层",
      url: baseUrl + url,
      queryParameters: {},
      symbol: (() => {
        if (type == 1) {
          return {}
        } else {
          return {
            merge: true,
            styleOptions: {
              width: 5,
              clampToGround: true,
              materialType: mars3d.MaterialType.LineFlow,
              materialOptions: {
                color: color,
                image: yellowLine,
                speed: 5
              },
              label: {
                text: '{name}',
                font_size: 14,
                color: "#ffffff",
                background: true,
                backgroundColor: 'rgb(0,172,199)',
                pixelOffsetY: -70,
                pixelOffsetScaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
                scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
              }
            }
          }
        }
      })(),
      flyTo: true,
    });

    map.addLayer(graphicLayer);

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'polylineJson',
      layer: graphicLayer,
      config: options,
      metadata: { projectName }
    });

    return graphicLayer;
  }

  /**
   * 添加点矢量图层 (兼容CustomMap API)
   * @param {Object} options - 点矢量图层配置
   * @param {string} options.id - 图层ID
   * @param {string} options.url - 数据URL
   * @param {string} options.name - 图层名称
   * @param {string} options.projectName - 项目名称
   * @param {string} options.color - 颜色
   * @param {string} options.icon - 图标路径
   * @returns {Object|null} 点矢量图层实例
   */
  addPointJson(options = {}) {
    const map = this._getMap();
    if (!map) return null;

    const {
      id,
      url,
      name,
      projectName,
      color,
      icon
    } = options;

    // 获取API基础URL
    const baseUrl = import.meta.env.VITE_APP_BASE_API;

    // 创建GeoJsonLayer
    const graphicLayer = new mars3d.layer.GeoJsonLayer({
      id: id,
      name: "点矢量图层",
      url: baseUrl + url,
      queryParameters: {},
      symbol: {
        merge: true,
        styleOptions: {
          image: icon,
          scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true,
          label: {
            text: '{name}',
            font_size: 14,
            color: "#ffffff",
            background: true,
            backgroundColor: 'rgb(0,172,199)',
            pixelOffsetY: -70,
            pixelOffsetScaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            scaleByDistance: new Cesium.NearFarScalar(7000, 1, 150000, 0.1),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
          }
        }
      },
      flyTo: true,
    });

    map.addLayer(graphicLayer);

    // 缓存图层信息
    this.businessLayers.set(id, {
      type: 'pointJson',
      layer: graphicLayer,
      config: options,
      metadata: { projectName }
    });

    return graphicLayer;
  }

  /**
   * 销毁业务图层管理器
   */
  destroy() {
    this.clearAllBusinessLayers();
    this.businessLayers.clear();
    this.mapEngine = null;
    this.layerManager = null;
  }
}

/**
 * 业务图层组合函数
 * @param {Object} mapEngine - 地图引擎实例
 * @param {Object} layerManager - 图层管理器实例
 * @returns {Object} 业务图层管理器API
 */
export function useBusinessLayers(mapEngine, layerManager) {
  const businessLayers = ref(null);

  /**
   * 初始化业务图层管理器
   */
  const initBusinessLayers = () => {
    businessLayers.value = new BusinessLayers(mapEngine, layerManager);
    return businessLayers.value;
  };

  /**
   * 获取业务图层管理器实例
   */
  const getBusinessLayers = () => businessLayers.value;

  /**
   * 销毁业务图层管理器
   */
  const destroy = () => {
    if (businessLayers.value) {
      businessLayers.value.destroy();
      businessLayers.value = null;
    }
  };

  return {
    businessLayers,
    initBusinessLayers,
    getBusinessLayers,
    destroy
  };
}
